package com.winit.cloudAgent.send;

import com.alibaba.fastjson.JSONObject;
import com.winit.cloudlink.Cloudlink;
import com.winit.cloudlink.event.Event;
import com.winit.cloudlink.event.EventOperation;
import com.winit.cloudlink.message.Message;
import com.winit.redis.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by wanglin on 2018/5/15.
 */
@Service
public class Send {
    @Resource
    private Cloudlink cloudlink;

    @Autowired
    RedisService redisService;

    public void handleJson(JSONObject jsonObject){
        String cloudLinkType = jsonObject.getString("cloudLinkType");
        String appId     = jsonObject.getString("appId");
        String  EventName = jsonObject.getString("eventName");
        JSONObject json = (JSONObject) JSONObject.parse(jsonObject.getString("parameter"));
        if("EVENT".equals(cloudLinkType) || StringUtils.isEmpty(cloudLinkType)){
            Event sendEvent = cloudlink.newEventBuilder().eventType(EventName)
                    .eventOperation(EventOperation.Create)
                    .module(jsonObject.getString("appType"))
                    .payload(json).build();
            redisService.setObj(sendEvent.getHeaders().getEventId(),jsonObject);
            cloudlink.publishEvent(sendEvent);
        }else{
            Message<JSONObject> message =cloudlink.newMessageBuilder() .direct(appId,EventName, json).build();
            redisService.setObj(message.getHeaders().getMessageId(),jsonObject);
            cloudlink.sendMessage(message);
        }
    }
}
